#include "led_driver.h"
#include "gd32f4xx.h"
#include "systick.h"
#include <stdbool.h>

static uint32_t LEDS[8] = {LED1, LED2, LED3, LED4, LED5, LED6, LED7, LED8};

void led_driver_config(void)
{
	// PC6:外设时钟使能
	rcu_periph_clock_enable(RCU_GPIOC); // 不要写成GPIOC

	// PC6:输出模式,推挽模式,低电平
	gpio_mode_set(GPIOC, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, LED_SW);
	gpio_output_options_set(GPIOC, GPIO_OTYPE_PP, GPIO_OSPEED_2MHZ, LED_SW);
	gpio_bit_reset(GPIOC, LED_SW);

	// 8个LED灯
	// PD8:外设时钟使能
	// PD8~PD15:输出模式,推挽输出,
	// 代码动态控制开关即高低电平,
	// 由于LED_SW输出高电平,故LED1~LED8低电平是开,高电平是关
	rcu_periph_clock_enable(RCU_GPIOD);

	uint8_t i;
	for (i = 0; i < 8; i++)
	{
		gpio_mode_set(GPIOD, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, LEDS[i]);
		gpio_output_options_set(GPIOD, GPIO_OTYPE_PP, GPIO_OSPEED_2MHZ, LEDS[i]);
	}
}

// 设置开关
//  由于LED_SW输出高电平,故LED1~LED8低电平是开,高电平是关
void led_driver_set(uint8_t leds_status)
{
	uint8_t i;
	for (i = 0; i < 8; i++)
	{
		uint8_t status = leds_status & (0b1U << i);
		if (status)
		{
			gpio_bit_reset(GPIOD, LEDS[i]);
		}
		else
		{
			gpio_bit_set(GPIOD, LEDS[i]);
		}
	}
}

// 全关
void led_driver_all_off()
{
	led_driver_set(0b00000000U);
}

// 全开
void led_driver_all_on()
{
	led_driver_set(0b11111111U);
}

// 跑马灯
void led_driver_test(void)
{
	static uint8_t led_status = 0b1U;
	static bool direction = true; // true:左移 false:右移

	led_driver_set(led_status);

	if (direction)
	{
		led_status <<= 1;
		if (led_status <= 0)
		{
			led_status = 0b10000000U;
			direction = false;
		}
	}
	else
	{
		led_status >>= 1;
		if (led_status <= 0)
		{
			led_status = 0b1U;
			direction = true;
		}
	}

	delay_1ms(800);
}
